package com.ponhu.ea2.goodsCenter.provider.service;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ponhu.ea2.dto.PhInventoryForCloudTradeDto;
import com.ponhu.ea2.dto.PhInventoryForGoodsCenterDto;
import com.ponhu.ea2.dto.PhInventoryForPurchaseDto;
import com.ponhu.ea2.entity.GoodsDataCreateorupdateLog;
import com.ponhu.ea2.entity.GoodsInventoryMd;
import com.ponhu.ea2.entity.Inventory;
import com.ponhu.ea2.enums.InventoryChannelEnum;
import com.ponhu.ea2.goodsCenter.provider.biz.InvokeStockCenterInterfaceService;
import com.ponhu.ea2.goodsCenter.provider.mapper.GoodsDataCreateorupdateLogMapper;
import com.ponhu.ea2.goodsCenter.provider.mapper.GoodsInventoryMdMapper;
import com.ponhu.ea2.goodsCenter.provider.mapper.InventoryMapper;
import com.ponhu.ea2.goodsCenter.provider.utils.DingTalkHandler;
import com.ponhu.ea2.goodsCenter.provider.utils.LocalDateUtil;
import com.ponhu.ea2.service.facade.GoodsCenterForChuangjiService;
import com.ponhu.ea2.service.facade.GoodsCenterForPonHuService;
import com.ponhu.ea2.service.facade.GoodsCenterForWMSService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author luyu
 * @create 2021-11-06 15:37
 */
@Slf4j
@Service
public class GoodsCenterPushThirdpartyService {

    @Resource
    GoodsDataCreateorupdateLogMapper goodsDataCreateorupdateLogMapper;

    @Resource
    GoodsCenterForWMSService goodsCenterForWMSService;

    @Resource
    InvokeStockCenterInterfaceService invokeStockCenterInterfaceService;

    @Resource
    GoodsCenterForChuangjiService goodsCenterForChuangjiService;

    @Resource
    InventoryMapper inventoryMapper;

    @Resource
    GoodsInventoryMdMapper goodsInventoryMdMapper;

    @Resource
    GoodsCenterForPonHuService goodsCenterForPonHuService;

    @Resource
    DingTalkHandler dingTalkHandler;

    @Resource
    PhinventoryToAmqpService phinventoryToAmqpService;

    /**
     * 推送巨沃商品档案信息
     */
    public void pushWms() {
        try {
            // 查询所有的状态为0,并且类型为wms的数据
            List<GoodsDataCreateorupdateLog> wms = goodsDataCreateorupdateLogMapper
                    .selectList(new LambdaQueryWrapper<GoodsDataCreateorupdateLog>()
                            .eq(GoodsDataCreateorupdateLog::getErrorStatus, 0)
                            .eq(GoodsDataCreateorupdateLog::getType, "wms"));
            // 调用推送巨沃的接口
            wms.stream().forEach(item -> {
                Inventory inventory = inventoryMapper.selectOne(new LambdaQueryWrapper<Inventory>()
                        .eq(Inventory::getInventoryCode, item.getInventoryCode()));
                Boolean bool = goodsCenterForWMSService.createOrUpdateGoodsForWms(inventory);
                if (bool) {
                    item.setErrorStatus("1");
                    goodsDataCreateorupdateLogMapper.updateById(item);
                    log.info("推送wms成功,货品编码为:{}", item.getInventoryCode());

                    // 对接钉钉保障提醒
                    dingTalkHandler.sendMsg(getSuccessMsg(item.getInventoryCode(), "巨沃"), new ArrayList());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 推送库存中心,初始化库存
     */
    public void pushStock() {
        try {
            // 查询所有的状态为0,并且类型为stock的数据
            List<GoodsDataCreateorupdateLog> stock = goodsDataCreateorupdateLogMapper
                    .selectList(new LambdaQueryWrapper<GoodsDataCreateorupdateLog>()
                            .eq(GoodsDataCreateorupdateLog::getErrorStatus, 0)
                            .eq(GoodsDataCreateorupdateLog::getType, "stock"));
            // 推送库存
            stock.stream().forEach(item -> {
                Inventory inventory = inventoryMapper.selectOne(new LambdaQueryWrapper<Inventory>()
                        .eq(Inventory::getInventoryCode, item.getInventoryCode()));
                GoodsInventoryMd goodsInventoryMd = goodsInventoryMdMapper.selectOne(
                        new LambdaQueryWrapper<GoodsInventoryMd>()
                                .eq(GoodsInventoryMd::getInventoryId,
                                        inventory.getId()));
                boolean bool = invokeStockCenterInterfaceService.createAndInitRealStockData(
                        goodsInventoryMd.getGoodsId(),
                        inventory.getId(),
                        inventory.getInventoryCode());
                if (bool) {
                    item.setErrorStatus("1");
                    goodsDataCreateorupdateLogMapper.updateById(item);
                    log.info("推送库存中心成功,货品编码为:{}", item.getInventoryCode());

                    // 对接钉钉保障提醒
                    dingTalkHandler.sendMsg(getSuccessMsg(item.getInventoryCode(), "库存中心"), new ArrayList());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void pushPonhuAdd() {
        // 查询所有的状态为0,并且类型为ponhu的数据
        List<GoodsDataCreateorupdateLog> ponhu = goodsDataCreateorupdateLogMapper
                .selectList(new LambdaQueryWrapper<GoodsDataCreateorupdateLog>()
                        .eq(GoodsDataCreateorupdateLog::getErrorStatus, 0)
                        .eq(GoodsDataCreateorupdateLog::getType, "ponhu_add"));

        ponhu.stream().forEach(item -> {
            Boolean bool = false;
            String inventoryCode = (String) JSONUtil.parseObj(item.getSourceData()).get("inventoryCode");
            Inventory inventory = inventoryMapper.selectOne(new LambdaQueryWrapper<Inventory>()
                    .eq(Inventory::getInventoryCode, inventoryCode));
            // 如果是云商
            if (InventoryChannelEnum.CLOUD_TRADE_JOINT_CONSIGNMENT.getCode()
                    .equals(inventory.getInventoryChannel())) {
                PhInventoryForCloudTradeDto phInventoryForCloudTradeDto =
                        JSONUtil.toBean(item.getSourceData(), PhInventoryForCloudTradeDto.class);
                bool = goodsCenterForPonHuService.createGoodsInfoForPonHu(phInventoryForCloudTradeDto);
            } else {
                PhInventoryForPurchaseDto phInventoryForPurchaseDto =
                        JSONUtil.toBean(item.getSourceData(), PhInventoryForPurchaseDto.class);
                bool = goodsCenterForPonHuService.createGoodsInfoForPonHu(phInventoryForPurchaseDto);
            }
            if (BooleanUtil.isTrue(bool)) {
                item.setErrorStatus("1");
                goodsDataCreateorupdateLogMapper.updateById(item);
                log.info("推送胖总管成功,货品编码为:{}", item.getInventoryCode());

                // 对接钉钉保障提醒
                dingTalkHandler.sendMsg(getSuccessMsg(item.getInventoryCode(), "发布胖总管"), new ArrayList());
            }
        });
    }

    public void pushPonhuUpdate() {
        // 查询所有的状态为0,并且类型为ponhu的数据
        List<GoodsDataCreateorupdateLog> ponhu = goodsDataCreateorupdateLogMapper
                .selectList(new LambdaQueryWrapper<GoodsDataCreateorupdateLog>()
                        .eq(GoodsDataCreateorupdateLog::getErrorStatus, 0)
                        .eq(GoodsDataCreateorupdateLog::getType, "ponhu_update"));

        ponhu.stream().forEach(item -> {
            Boolean bool = false;
            String inventoryCode = (String) JSONUtil.parseObj(item.getSourceData()).get("inventoryCode");
            Inventory inventory = inventoryMapper.selectOne(new LambdaQueryWrapper<Inventory>()
                    .eq(Inventory::getInventoryCode, inventoryCode));
            // 如果是云商
            if (InventoryChannelEnum.CLOUD_TRADE_JOINT_CONSIGNMENT.getCode()
                    .equals(inventory.getInventoryChannel())) {
                PhInventoryForCloudTradeDto phInventoryForCloudTradeDto =
                        JSONUtil.toBean(item.getSourceData(), PhInventoryForCloudTradeDto.class);
                bool = goodsCenterForPonHuService.updateGoodsInfoForPonhu(phInventoryForCloudTradeDto);
            } else {
                PhInventoryForGoodsCenterDto phInventoryForGoodsCenterDto =
                        JSONUtil.toBean(item.getSourceData(), PhInventoryForGoodsCenterDto.class);
                bool = goodsCenterForPonHuService.updateGoodsInfoForPonhu(phInventoryForGoodsCenterDto);
            }
            if (BooleanUtil.isTrue(bool)) {
                item.setErrorStatus("1");
                goodsDataCreateorupdateLogMapper.updateById(item);
                log.info("推送胖总管成功,货品编码为:{}", item.getInventoryCode());

                // 对接钉钉保障提醒
                dingTalkHandler.sendMsg(getSuccessMsg(item.getInventoryCode(), "更新胖总管"), new ArrayList());
            }
        });
    }

    /**
     * 补推创纪云
     */
    public void pushChuangjiCloud() {
        try {
            // 查询创纪云所有的状态为0的数据
            List<GoodsDataCreateorupdateLog> stock = goodsDataCreateorupdateLogMapper
                    .selectList(new LambdaQueryWrapper<GoodsDataCreateorupdateLog>()
                            .eq(GoodsDataCreateorupdateLog::getErrorStatus, 0)
                            .eq(GoodsDataCreateorupdateLog::getType, "chuangjiCloud"));
            // 推送库存
            stock.stream().forEach(item -> {
                Inventory inventory = inventoryMapper.selectOne(new LambdaQueryWrapper<Inventory>()
                        .eq(Inventory::getInventoryCode, item.getInventoryCode()));
                Boolean bool = goodsCenterForChuangjiService.phInventoryUpdateToChuangji(inventory.getId());
                if (bool) {
                    item.setErrorStatus("1");
                    goodsDataCreateorupdateLogMapper.updateById(item);
                    log.info("推送创纪云成功,货品编码为:{}", item.getInventoryCode());
                    // 对接钉钉保障提醒
                    dingTalkHandler.sendMsg(getSuccessMsg(item.getInventoryCode(), "创纪云"), new ArrayList());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getSuccessMsg(String code, String type) {
        StringBuffer msg = new StringBuffer();
        msg.append("商品中心的货品编码：").append(code).append("，时间：").append(LocalDateUtil.getNowLocalDateTime()).append("，补推").append(type).append("成功!");
        return msg.toString();
    }

    /**
     * 同步信息
     * @param pushMode
     * @param list
     */
    public String pushInventoryToThirdParty(JSONArray pushMode, List<Inventory> list) {
        StringBuffer strbuf = new StringBuffer();
        int count = list.size();
        pushMode.parallelStream().forEach(i -> {
            if(i.equals("chuangjiyun")){
                AtomicInteger atomicChuangjiyun = new AtomicInteger();
                list.parallelStream().forEach(item -> {
                    if(goodsCenterForChuangjiService.phInventoryUpdateToChuangji(item.getId())){
                        atomicChuangjiyun.incrementAndGet();
                    }
                });
                strbuf.append("定时任务-补推数据,")
                        .append("补推创纪云"+count+"条,")
                        .append("成功"+atomicChuangjiyun+"条,")
                        .append("失败"+(count-atomicChuangjiyun.intValue())+"条");
            }
            if(i.equals("juwo")){
                AtomicInteger atomicJuwo = new AtomicInteger();
                list.parallelStream().forEach(item -> {
                    if (goodsCenterForWMSService.createOrUpdateGoodsForWms(item)){
                        atomicJuwo.incrementAndGet();
                    }
                });
                strbuf.append("定时任务-补推数据,")
                        .append("补推巨沃"+count+"条,")
                        .append("成功"+atomicJuwo+"条,")
                        .append("失败"+(count-atomicJuwo.intValue())+"条");
            }
        });
        return strbuf.toString();
    }

    /**
     * 推送会员小程序
     */
    public void pushDataToApplet() {
        // 查询推送会员小程序失败的数据
        List<GoodsDataCreateorupdateLog> goodsDataCreateorupdateLog = goodsDataCreateorupdateLogMapper
                .selectList(new LambdaQueryWrapper<GoodsDataCreateorupdateLog>()
                        .eq(GoodsDataCreateorupdateLog::getErrorStatus, 0)
                        .eq(GoodsDataCreateorupdateLog::getType, "Applet"));
        goodsDataCreateorupdateLog.stream().forEach(item -> {
            phinventoryToAmqpService.pushDataToAmqp(Arrays.asList(item.getInventoryCode()),Integer.valueOf(item.getSourceData()));
            item.setErrorStatus("1");
            goodsDataCreateorupdateLogMapper.updateById(item);
        });

    }
}
